package org.game.module.event.handler;

import java.util.List;
import java.util.Map;

import org.cfg.EventConditionCfg;
import org.cfg.TriggerEventCfg;
import org.cfg.cache.EventConditionCfgCache;
import org.cfg.cache.TriggerEventCfgCache;
import org.game.constant.ElementCollectionConstant;
import org.game.manager.ElementCollectManager;
import org.game.plugin.event.GameEvent;
import org.game.plugin.event.GameEventHandler;
import org.game.plugin.event.GameEventListener;
import org.game.plugin.event.GameEventStack;

/**
 * @author : DengYing
 * @CreateDate : 2017年8月31日 下午1:33:30
 * @Description ：触发型事件处理器
 */
public class TriggerEventHandler implements GameEventHandler {

	@Override
	public void onEvent(GameEventListener listener, GameEvent event) {
		int conditionType = event.getConditionType();
		if(conditionType == 0){
			return;
		}

		// 根据事件类型取得触发型事件配置
		List<TriggerEventCfg> triggerEvents = TriggerEventCfgCache.me().getByEventConditionId(conditionType);
		for (TriggerEventCfg triggerEventCfg : triggerEvents) {
			// 取得事件条件
			EventConditionCfg eventConditionCfg = EventConditionCfgCache.me().getById(triggerEventCfg.getEventConditionId());
			if (eventConditionCfg==null) {
				return;
			}

			int conditionId = triggerEventCfg.getEventConditionId();

			// 如果条件参数为空，则任务成功触发条件
			Map params = triggerEventCfg.getParams();
			boolean trigger = (params == null || params.isEmpty());
			
			
			
			if (trigger) {
				eventResult(event,triggerEventCfg.getResult(),null);
				ElementCollectManager.recordElement(event.getPlayer(), ElementCollectionConstant.KEY_EVENT,triggerEventCfg.getId());
			}else {
				event.push(new GameEventStack(eventConditionCfg.getEventId(),conditionId, params, 0, 0, trigger));
				listener.onEvent(event);
				GameEventStack eventStack = event.peek();
				// 条件触发成功
				if(eventStack.isTrigger()){
					eventResult(event,triggerEventCfg.getResult(),null);
					ElementCollectManager.recordElement(event.getPlayer(), ElementCollectionConstant.KEY_EVENT,triggerEventCfg.getId());
				}
			}
		}
	}
	

}
